package com.acooly.module.openapi.client.file.impl;

import com.acooly.core.utils.net.SFTP;
import com.acooly.module.openapi.client.file.domain.FileHandlerOrder;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

@Slf4j
@Getter
@Setter
public abstract class AbstractSftpFileHandler extends AbstractFileHandler {

    /**
     * sftp args
     */
    private String host;
    private int port;
    private String username;
    private String password;


    @Override
    public File doDownload(FileHandlerOrder order) {
        try {
            String localFilePath = getLocalFilePath(order);
            String serverFilePath = getServerFilePath(order);
            log.info("SFTP下载 serverPath: {}", serverFilePath);
            log.info("SFTP下载 local Path: {}", localFilePath);
            Session session = SFTP.createSession(host, port, username, password);
            ChannelSftp channelSftp = SFTP.createChannel(session);
            SFTP.download(channelSftp, serverFilePath, localFilePath);
            log.info("SFTP下载 【成功】");
            return new File(localFilePath);
        } catch (Exception e) {
            throw new RuntimeException("SFTP下载 【失败】.", e);
        }
    }

    /**
     * 生成本地存储文件全路径
     *
     * @param order
     * @return
     */
    protected abstract String getLocalFilePath(FileHandlerOrder order);

    /**
     * 生成服务器端文件全路径
     *
     * @param order
     * @return
     */
    protected abstract String getServerFilePath(FileHandlerOrder order);


}
